#include "widget.h"
#include "ui_widget.h"



Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{

    newidget = new QWidget ();

    newidget->setWindowTitle("客户端");

    m_tcp = new QTcpSocket(this);

    lab_1 = new QLabel("ip :");
    lab_2 = new QLabel("端口:");

    btn_tcps = new QPushButton("连接服务器");

    connect(m_tcp,&QTcpSocket::readyRead,this,analyze);
    connect(btn_tcps, SIGNAL(clicked()), this, SLOT(connect_tcp()));
    connect(this, &Widget::gamestart, this, &Widget::start_game);
    connect(this, &Widget::kaishi, this, &Widget::game_start);
    connect(this, &Widget::cchange, this, &Widget::if_me);
    connect(this, &Widget::chips, this, &Widget::if_mechip);

    HLayou_01 = new QHBoxLayout;
    HLayou_02 = new QHBoxLayout;
    HLayou_03 = new QHBoxLayout;
    HLayou_04 = new QHBoxLayout;

    VLayou01 = new QVBoxLayout();

    w_ip = new QTextEdit;
    w_port = new QTextEdit;

    w_record = new QPlainTextEdit;

    w_record->setReadOnly(true);

    w_ip->setText("127.0.0.1");
    w_port->setText("9933");

    HLayou_01->addWidget(lab_1);
    HLayou_01->addWidget(w_ip);

    HLayou_02->addWidget(lab_2);
    HLayou_02->addWidget(w_port);

    HLayou_03->addWidget(btn_tcps);

    HLayou_04->addWidget(w_record);

    VLayou01->addLayout(HLayou_01);
    VLayou01->addLayout(HLayou_02);
    VLayou01->addLayout(HLayou_03);
    VLayou01->addLayout(HLayou_04);

    newidget->setLayout(VLayou01);

    newidget->show();

    ui->setupUi(this);

    //初始化w_deck
    for(int i=0;i<15;i++){
        w_card[i] = new Card (i+1);
    }
    for(int i=0;i<6;i++){
        w_hand[i] = new Hand (w_card[i]);
    }
    for(int i=0;i<6;i++){
        w_plyr[i] = new Player (w_hand[i]);
    }
    w_deck = new Deck(w_plyr);

    pushbtn = new QPushButton("开始游戏");
    btn_show = new QPushButton("开牌");
    btn_change = new QPushButton("换牌");
    btn_check = new QPushButton("确认");
    btn_reject = new QPushButton("取消");
    btn_pub = new QPushButton("公示");
    btn_raise = new QPushButton("加注");
    btn_call = new QPushButton("跟注");
    btn_fold = new QPushButton("弃牌");
    btn_all = new QPushButton("all-in");

    btn_change->setEnabled(false);
    btn_pub->setEnabled(false);
    btn_check->setEnabled(false);
    btn_reject->setEnabled(false);
    pushbtn->setEnabled(false);
    btn_raise->setEnabled(false);
    btn_call->setEnabled(false);
    btn_fold->setEnabled(false);
    btn_all->setEnabled(false);

    connect(pushbtn, SIGNAL(clicked()), this, SLOT(game_start()));
    connect(btn_change, SIGNAL(clicked()), this, SLOT(if_change()));
    connect(btn_show, SIGNAL(clicked()), this, SLOT(show_card()));
    connect(btn_check, SIGNAL(clicked()), this, SLOT(c_change()));
    connect(btn_reject, SIGNAL(clicked()), this, SLOT(r_change()));
    connect(btn_pub, SIGNAL(clicked()), this, SLOT(if_pub()));
    connect(btn_raise, SIGNAL(clicked()), this, SLOT(w_raise()));
    connect(btn_call, SIGNAL(clicked()), this, SLOT(w_call()));
    connect(btn_fold, SIGNAL(clicked()), this, SLOT(w_fold()));
    connect(btn_all, SIGNAL(clicked()), this, SLOT(w_all()));

    spin_raise = new QSpinBox();
    spin_raise->setRange(10, 1000);

    record = new QPlainTextEdit;

    txt[0] = "玩家1";
    txt[1] = "玩家2";
    txt[2] = "玩家3";
    txt[3] = "玩家4";
    txt[4] = "玩家5";
    txt[5] = "玩家6";

    l_player[0] = new QLabel("玩家1");
    l_player[1] = new QLabel("玩家2");
    l_player[2] = new QLabel("玩家3");
    l_player[3] = new QLabel("玩家4");
    l_player[4] = new QLabel("玩家5");
    l_player[5] = new QLabel("玩家6");

    for(int i=0; i<6; i++){
        l_player[i]->setFixedSize(300,100);
    }

    w_abandon = new QLabel("弃牌区：");
    w_public = new QLabel("公示区：");

    w_abandon->setFixedSize(100 ,100);
    w_public->setFixedSize(100 ,100);

    VLayou1 = new QVBoxLayout;
    VLayou2 = new QVBoxLayout;
    VLayou3 = new QVBoxLayout;
    VLayou4 = new QVBoxLayout;
    VLayou5 = new QVBoxLayout;
    HLayou = new QHBoxLayout;

    VLayou1->addWidget(l_player[0]);
    VLayou1->addWidget(l_player[1]);
    VLayou1->addWidget(l_player[2]);
    VLayou1->addWidget(w_abandon);

    VLayou2->addWidget(l_player[3]);
    VLayou2->addWidget(l_player[4]);
    VLayou2->addWidget(l_player[5]);
    VLayou2->addWidget(w_public);

    VLayou3->addWidget(btn_change);
    VLayou3->addWidget(btn_check);
    VLayou3->addWidget(btn_reject);
    VLayou3->addWidget(btn_pub);

    VLayou4->addWidget(spin_raise);
    VLayou4->addWidget(btn_raise);
    VLayou4->addWidget(btn_call);
    VLayou4->addWidget(btn_fold);
    VLayou4->addWidget(btn_all);


    HLayou->addLayout(VLayou1);
    HLayou->addLayout(VLayou2);
    HLayou->addLayout(VLayou3);
    HLayou->addLayout(VLayou4);

    VLayou5->addLayout(HLayou);
    VLayou5->addWidget(record);

    setLayout(VLayou5);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::createShuffledarr(int arr[15])
{
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine engine(seed);
    std::shuffle(arr, arr + 15, engine);

}

//开始游戏
void Widget::game_start()
{

    w_deck->createShuffledCardDeck(Shuffled);
    w_deck->begin();

    record->clear();
    record->appendPlainText("新的一轮游戏开始");
    record->appendPlainText("你的底牌是" + QString::number(w_deck->m_player[w_deck->my_plyr-1]->get_rank()));
    record->appendPlainText("现在是玩家" + QString::number(w_deck->m_num%6 + 1) + "的回合");

    for (int i = 0; i < 6; i++) {
//        qDebug() << w_deck->m_player[i]->get_rank();
    }

    for(int i=0;i<6;i++){
        if(w_deck->m_player[i]->get_rank()%2==0){
            l_player[i]->setStyleSheet("background-color: blue;");
        }
        else l_player[i]->setStyleSheet("background-color: green;");
    }

    //更新每个人的剩余筹码
    QString text[6];
    for(int i =0 ; i< 6 ; i++){
        txt[i] = "玩家" + QString::number(i + 1) + "\n筹码：" + QString::number(w_deck->m_player[i]->get_chip()) + "\n当前下注:";
        text[i] = txt[i] + "10";//底注
        l_player[i]->setText(text[i]);
    }

    w_abandon->setText("弃牌区：");
    w_public->setText("公示区：");

    if_me();
}

void Widget::start_chip()
{
    btn_raise->setEnabled(true);
    btn_call->setEnabled(true);
    btn_fold->setEnabled(true);
    btn_all->setEnabled(true);

}

//开牌
void Widget::show_card(int maxscore)
{
    //亮牌
    QString text[6];
    for (int i = 0; i < 6; i++) {
            text[i] = "玩家" + QString::number(i+1) + "底牌为 " + QString::number(w_deck->m_player[i]->get_rank()) + "\n当前下注:" + QString::number(w_deck->m_player[i]->get_c_chip());
            l_player[i]->setText(text[i]);
    }

    int chip_sum = 0;
    int chip_pre = 0;
    int win_num = 0;
    for(int i=0; i<6; i++){
        chip_sum += w_deck->m_player[i]->get_c_chip();
        if(w_deck->m_player[i]->score == maxscore){
            win_num++;
        }
    }

    chip_pre = chip_sum / win_num;

    QString txt;

    for(int i=0; i<6; i++){
        if(w_deck->m_player[i]->score == maxscore){
            w_deck->m_player[i]->change_chip(w_deck->m_player[i]->get_chip() + chip_pre - w_deck->m_player[i]->get_c_chip());

            txt.append(QString::number(i + 1) + " ");
        }
    }

    record->appendPlainText("玩家" + txt + "赢得筹码！本轮总下注为" + QString::number(chip_sum));

//    for(int i=0; i<6; i++){
//        if(i!=winner){
//        chip_sum += w_deck->m_player[i]->get_c_chip();
//        w_deck->m_player[i]->change_chip(w_deck->m_player[i]->get_chip() -  w_deck->m_player[i]->get_c_chip());
//        }
//    }

//    w_deck->m_player[winner]->change_chip(w_deck->m_player[winner]->get_chip() + chip_sum);

//    record->appendPlainText("玩家" + QString::number(winner + 1) + "赢得所有筹码！本轮总下注为" + QString::number(chip_sum + w_deck->m_player[winner]->get_c_chip()));

}

void Widget::if_change()
{
    record->appendPlainText("你可以选择换的牌是 " + QString::number(w_deck->card_deck.at(w_deck->m_num)->get_rank()));

    btn_check->setEnabled(true);
    btn_reject->setEnabled(true);
    btn_change->setEnabled(false);
    btn_pub->setEnabled(false);

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("change");

    // 将数据回传给服务器
    m_tcp->write(data);
}

void Widget::c_change()
{
    QString text_1 = w_abandon->text() + " " + QString::number(w_deck->m_player[w_deck->m_num%6]->get_rank()) + " ,";
    w_abandon->setText(text_1);

    w_deck->m_player[w_deck->m_num%6]->set_hand(w_deck->card_deck.at(w_deck->m_num));

    if(w_deck->m_player[w_deck->m_num%6]->get_rank()%2==0){
                    l_player[w_deck->m_num%6]->setStyleSheet("background-color: blue;");
                }
                else l_player[w_deck->m_num%6]->setStyleSheet("background-color: green;");

    btn_check->setEnabled(false);
    btn_reject->setEnabled(false);

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("cchange");

    // 将数据回传给服务器
    m_tcp->write(data);
}

void Widget::r_change()
{
    //将这张牌放到弃牌区
    QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip());
    l_player[w_deck->m_num%6]->setText(text);

    QString text_1 = w_abandon->text() + " " + QString::number(w_deck->card_deck.at(w_deck->m_num)->get_rank()) + " ,";
    w_abandon->setText(text_1);

    btn_check->setEnabled(false);
    btn_reject->setEnabled(false);

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("rchange");

    // 将数据回传给服务器
    m_tcp->write(data);
}

void Widget::if_pub()
{
    QString text = w_public->text() + " " + QString::number(w_deck->card_deck.at(w_deck->m_num)->get_rank()) + " ,";
    w_public->setText(text);

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("pub");

    // 将数据回传给服务器
    m_tcp->write(data);

    btn_change->setEnabled(false);
    btn_pub->setEnabled(false);

}

void Widget::w_raise()
{

    if(w_deck->m_player[w_deck->m_num%6]->if_stay)
    {
        w_deck->m_chip = spin_raise->value() + w_deck->m_chip;
        w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_chip);

        QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip());
        l_player[w_deck->m_num%6]->setText(text);

        w_deck->m_left = 5 - w_deck->m_all - w_deck->m_fold;
    }

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型
    out << 5 ;

    out << spin_raise->value() << QString("raise");

    // 将数据回传给服务器
    m_tcp->write(data);

    btn_raise->setEnabled(false);
    btn_call->setEnabled(false);
    btn_fold->setEnabled(false);
    btn_all->setEnabled(false);

}

void Widget::w_fold()
{
    w_deck->m_player[w_deck->m_num%6]->if_stay = false;

    QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip()) + "\n已弃牌";
    l_player[w_deck->m_num%6]->setText(text);

    w_deck->m_left--;
    w_deck->m_fold++;

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("fold");

    // 将数据回传给服务器
    m_tcp->write(data);

    btn_raise->setEnabled(false);
    btn_call->setEnabled(false);
    btn_fold->setEnabled(false);
    btn_all->setEnabled(false);

}

void Widget::w_call()
{
    if(w_deck->m_player[w_deck->m_num%6]->if_stay)
    {
         w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_chip);

         QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip());
         l_player[w_deck->m_num%6]->setText(text);

         w_deck->m_left--;
    }

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("call");

    // 将数据回传给服务器
    m_tcp->write(data);

    btn_raise->setEnabled(false);
    btn_call->setEnabled(false);
    btn_fold->setEnabled(false);
    btn_all->setEnabled(false);
}

void Widget::w_all()
{
    if(w_deck->m_player[w_deck->m_num%6]->if_stay)
    {
         w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_player[w_deck->m_num%6]->get_chip());
         w_deck->m_player[w_deck->m_num%6]->if_all = true ;

         QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip()) + "\n已all-in";
         l_player[w_deck->m_num%6]->setText(text);

         w_deck->m_left--;
         w_deck->m_all++;
    }

    w_deck->next_plyr();

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    // 数据类型，2表示字符串
    out << 2 ;

    out << QString("all");

    // 将数据回传给服务器
    m_tcp->write(data);

    btn_raise->setEnabled(false);
    btn_call->setEnabled(false);
    btn_fold->setEnabled(false);
    btn_all->setEnabled(false);
}

void Widget::connect_tcp()
{
    QString ip = w_ip->toPlainText();
    unsigned short port = w_port->toPlainText().toUShort();
    m_tcp->connectToHost(QHostAddress(ip),port);
    w_record->appendPlainText("已连接到服务器");

}

void Widget::start_game()
{
    newidget->close();
    this->show();
    record->appendPlainText("你是玩家" + QString::number(w_deck->my_plyr));
}

//判断是不是轮到自己
void Widget::if_me()
{
    if((w_deck->my_plyr == w_deck->m_num%6+1)&&(w_deck->m_num < 12 + w_deck->m_dealer)){
        btn_change->setEnabled(true);
        btn_pub->setEnabled(true);
    }
}

//判断是不是到自己下注
void Widget::if_mechip()
{
    if ((w_deck->my_plyr == w_deck->m_num%6+1)&&(w_deck->m_left != 0)){
        if (w_deck->m_player[w_deck->m_num%6]->if_stay&&!(w_deck->m_player[w_deck->m_num%6]->if_all))
        {
            btn_raise->setEnabled(true);
            btn_call->setEnabled(true);
            btn_fold->setEnabled(true);
            btn_all->setEnabled(true);
        }
        else {
            w_deck->next_plyr();
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);

            // 数据类型，2表示字符串
            out << 2 ;

            out << QString("next");
        }
    }
}

//处理服务器发来的信号
void Widget::analyze()
{
    QByteArray byteArray = m_tcp->readAll();
    QDataStream in(&byteArray, QIODevice::ReadOnly);

    int dataType;
    int chip;

    in >> dataType;

    if (dataType == 2) {
        // 读取字符串
        QString signalName;
        in >> signalName;

        // 处理字符串数据
        if (signalName == "gamestart") {
            emit gamestart();
        }

        if (signalName == "kaishi") {
            emit kaishi();
        }

        if (signalName == "change") {
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择换牌");
        }

        if (signalName == "cchange") {
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "确认换牌");

            QString text_1 = w_abandon->text() + " " + QString::number(w_deck->m_player[w_deck->m_num%6]->get_rank()) + " ,";
            w_abandon->setText(text_1);

            w_deck->m_player[w_deck->m_num%6]->set_hand(w_deck->card_deck.at(w_deck->m_num));

            if(w_deck->m_player[w_deck->m_num%6]->get_rank()%2==0){
                            l_player[w_deck->m_num%6]->setStyleSheet("background-color: blue;");
                        }
            else l_player[w_deck->m_num%6]->setStyleSheet("background-color: green;");

            w_deck->next_plyr();

            emit cchange();
        }

        if (signalName == "rchange") {
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "放弃换牌");

            QString text_1 = w_abandon->text() + " " + QString::number(w_deck->card_deck.at(w_deck->m_num)->get_rank()) + " ,";
            w_abandon->setText(text_1);
            w_deck->next_plyr();

            emit cchange();
        }

        if (signalName == "pub"){
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择公示");

            QString text = w_public->text() + " " + QString::number(w_deck->card_deck.at(w_deck->m_num)->get_rank()) + " ,";
            w_public->setText(text);
            w_deck->next_plyr();

            emit cchange();
        }

        if (signalName == "fold"){
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择弃牌");

            w_deck->m_player[w_deck->m_num%6]->if_stay = false;

            QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip()) + "\n已弃牌";
            l_player[w_deck->m_num%6]->setText(text);

            w_deck->m_left--;
            w_deck->m_fold++;

            w_deck->next_plyr();

            emit chips();
        }

        if (signalName == "call"){
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择跟注");

            w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_chip);

            QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip());
            l_player[w_deck->m_num%6]->setText(text);

            w_deck->m_left--;

            w_deck->next_plyr();

            emit chips();
        }

        if (signalName == "all"){
            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择all-in");

            w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_player[w_deck->m_num%6]->get_chip());
            w_deck->m_player[w_deck->m_num%6]->if_all = true ;

            QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip()) + "\n已all-in";
            l_player[w_deck->m_num%6]->setText(text);

            w_deck->m_left--;
            w_deck->m_all++;

            w_deck->next_plyr();

            emit chips();
        }

        if (signalName == "next"){
            w_deck->next_plyr();

            emit chips();
        }

        if (signalName == "startchip"){
            emit chips();
        }

    }


     else if (dataType == 1) {
        // 读取整型数组
        for (int i = 0; i < 15; i++) {
            in >> Shuffled[i];
        }
    }

    else if (dataType == 3){
        for (int i = 0; i < 15; i++) {
            in >> Shuffled[i];
        }

        QString signalName;
        in >> signalName;
        if (signalName == "kaishi") {
             emit kaishi();
        }
    }

    else if (dataType == 4){
        in >> w_deck->my_plyr;

        w_record->appendPlainText("你是玩家" + QString::number(w_deck->my_plyr));
    }

    else if (dataType == 5){
        QString signalName;
        in >> chip >> signalName;
        if(signalName == "raise"){           
            w_deck->m_chip = chip + w_deck->m_chip;
            w_deck->m_player[w_deck->m_num%6]->change_c_chip(w_deck->m_chip);

            record->appendPlainText("玩家" + QString::number(w_deck->m_num%6+1) + "选择加注到" + QString::number(w_deck->m_chip));

            w_deck->m_left = 5 - w_deck->m_all - w_deck->m_fold;

            QString text = txt[w_deck->m_num%6] + QString::number(w_deck->m_player[w_deck->m_num%6]->get_c_chip());
            l_player[w_deck->m_num%6]->setText(text);

            w_deck->next_plyr();

            emit chips();
        }

    }

    else if (dataType == 6){
        QString signalName;
        int maxscore;

        in >> maxscore;
        for (int i = 0; i < 6; i++) {
            in >> w_deck->m_player[i]->score;
        }

        in >> signalName;

        if (signalName == "kaipai"){
            show_card(maxscore);
        }
    }

}
